package com.hnxxxy.common.task;


import com.hnxxxy.common.AjaxRtnEntity.AjaxRtnEntity;
import com.hnxxxy.common.task.pojo.TaskPojo;
import com.hnxxxy.common.task.service.CstTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

@RestController
public class TaskController {
    @Autowired
    private TaskPojo taskPojo;

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private ScheduledFuture<?> future;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @RequestMapping("/startCron")
    public AjaxRtnEntity startCron() {
        AjaxRtnEntity ajaxRtnEntity=new AjaxRtnEntity();
        future= threadPoolTaskScheduler.schedule(new CstTaskService(), new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                return new CronTrigger(taskPojo.getCorn()).nextExecutionTime(triggerContext);
            }
        });
        ajaxRtnEntity.setCode(1);
        ajaxRtnEntity.setCodeInfo(taskPojo.getCorn().toString()+"任务启动成功");
        return ajaxRtnEntity;

    }

    @RequestMapping("/stopCron")
    public AjaxRtnEntity stopCron() {
        AjaxRtnEntity ajaxRtnEntity=new AjaxRtnEntity();
        if (future != null) {
            future.cancel(true);
        }
        ajaxRtnEntity.setCode(1);
        ajaxRtnEntity.setCodeInfo(taskPojo.getCorn().toString()+"任务终止成功");
        return  ajaxRtnEntity;
    }


}
